import { _decorator, Component, EventTouch, game, Input, input, Mat4, math, misc, Node, Quat, SceneAsset, Vec2, Vec3 } from 'cc';
import { levelBgpng } from './testScript/levelBgpng';
const { ccclass, property } = _decorator;


enum tipscurState {
    MOVE,
    ROTATE,
    REVERSAL
}

@ccclass('tip2Script')
export class tip2Script extends Component {

    curcurState: tipscurState = null

    clickInterval: number = 0.3  // 双击间隔时间，单位秒
    lastClickTime: number = 0   // 上次点击时间

    private startTouchPos: Vec2 = new Vec2(0, 0);  // 起始触摸位置
    private startAngle: number = 0;  // 记录触摸时的旋转角度

    // 标志位：是否正在移动
    private isMoving: boolean = false;
    // 旋转标志位：是否旋转
    private isRotation: boolean = false;

    private chileNum = 0

    polygonsInfo: polygonInfo[] = [
        // {x:83,y:-225,angle:[180,-180],reverse:-1},//金黄
        // {x:424,y:-225,angle:[180,-180],reverse:-1},//紫色
        // {x:-320,y:-225,angle:[0,360],reverse:1},//橙黄
        // {x:504,y:-225,angle:[90,-270],reverse:1},//绿色

    ]

    //当前碎片的位置(x,y,反转，角度)
    curTargetInfo: polygonInfo = null




    protected onLoad(): void {
        //随机生成位置
        this.node.setPosition(new Vec3(math.randomRangeInt(1000, 1900), math.randomRangeInt(-800, 400)))  //Math.random(1200,1720)
        //角度
        this.node.angle = math.randomRangeInt(1, 9) * 45
        this.chileNum = this.node.getSiblingIndex();
        this.polygonsInfo = this.node.getParent().getParent().getComponent(levelBgpng).polygonsInfo
        this.curTargetInfo = this.polygonsInfo[this.chileNum]



    }

    start() {
        this.curcurState = tipscurState.MOVE
        // 监听触摸事件
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);

    }

    onTouchStart(event: EventTouch) {
        // 记录触摸的起始位置
        this.startTouchPos = event.getLocation();

        // 计算当前触摸点与节点中心的角度
        this.startAngle = this.getAngleFromNodeCenter(this.startTouchPos);

    }
    onTouchMove(event: EventTouch) {
        // 如果是可移动状态，允许节点移动
        console.log("当前状态", this.curcurState)
        const touch = event.touch!;
        const currentPos = touch.getLocation();
        if (this.curcurState === tipscurState.MOVE) {
            // let touchLocation = event.getLocation();
            this.isMoving = true; // 标记为正在移动
            // this.node.translate(new Vec3(event.getUIDelta().x, event.getUIDelta().y))
            this.node.setPosition(new Vec3(this.node.getPosition().x + event.getUIDelta().x * 2, this.node.getPosition().y + event.getUIDelta().y * 2, 0))
        }
        // 如果是可旋转状态，允许节点旋转
        else if (this.curcurState === tipscurState.ROTATE) {
            this.isRotation = true;
            // 获取触摸的x轴变化量
            let X = event.getDelta().x;

            // 计算当前节点的旋转角度
            this.node.angle += X;

            // 保证角度始终在 -360 到 360 之间
            if (this.node.angle > 360) {
                this.node.angle -= 360;
            } else if (this.node.angle < -360) {
                this.node.angle += 360;
            }

            // 将角度对齐到最接近的45度倍数
            let alignedAngle = Math.round(this.node.angle / 45) * 45;

            // 根据当前角度和对齐角度的差值来调整角度
            let difference = alignedAngle - this.node.angle;

            // 如果差值大于 0，旋转过渡到对齐角度
            if (Math.abs(difference) > 0) {
                // 使用线性插值来实现平滑过渡
                this.node.angle += difference * 0.1;  // 0.1 为平滑度系数，可以根据需要调整
            }
        }

    }


    private getAngleFromNodeCenter(touchPos: Vec2): number {
        const nodePos = this.node.position;  // 节点的世界位置
        const dx = touchPos.x - nodePos.x;  // 触摸点与节点的X轴差值
        const dy = touchPos.y - nodePos.y;  // 触摸点与节点的Y轴差值

        // 使用 atan2 函数来计算角度
        const angleInRadians = Math.atan2(dy, dx);

        // 转换为角度（度数）
        return misc.radiansToDegrees(angleInRadians);
    }

    onTouchEnd(event: EventTouch) {

        //移动后判断是否拼图成功
        if (this.curcurState === tipscurState.MOVE) {

            //快到目标位置时的吸附功能
            this.toMoveTarget()
            this.scheduleOnce(() => {
                game.emit("gameVictory")

                // console.log("移动后监听是否位置正确")
            }, 0.2)
        }

        const currentTime = new Date().getTime() / 1000; // 获取当前时间戳（秒）

        // 判断是否为双击
        if (currentTime - this.lastClickTime < this.clickInterval) {
            this.onDoubleClick();  // 双击回调
        } else {
            this.onSingleClick();  // 单击回调
        }

        // 更新上次点击时间
        this.lastClickTime = currentTime;

    }


    protected onDisable(): void {
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }


    //快到目标位置时的吸附功能
    toMoveTarget() {

        console.log(this.curTargetInfo.angle[1], this.curTargetInfo.angle[0], this.node.angle, this.curTargetInfo.reverse, this.node.scale.x)
        if ((this.curTargetInfo.angle[1] == this.node.angle || this.curTargetInfo.angle[0] == this.node.angle) && this.curTargetInfo.reverse == this.node.scale.x) {

            //x的差值
            const X = math.bits.abs(math.bits.abs(this.node.getPosition().x) - math.bits.abs(this.curTargetInfo.x));
            const Y = math.bits.abs(math.bits.abs(this.node.getPosition().y) - math.bits.abs(this.curTargetInfo.y));
            console.log(this.node.getPosition().x, this.curTargetInfo.x, X)
            console.log(this.node.getPosition().y, this.curTargetInfo.y, Y)
            if (X < 60 && Y < 60) {
                this.node.setPosition(new Vec3(this.curTargetInfo.x, this.curTargetInfo.y, 0));
            }

        }
    }

    onSingleClick() {

        if (this.curcurState === tipscurState.ROTATE) {
            // 将角度对齐到最接近的45度倍数
            let alignedAngle = Math.round(this.node.angle / 45) * 45;
            this.node.angle = alignedAngle
            // this.isTouching = false;
        }

        if (this.isMoving || this.isRotation) {
            this.isMoving = false; // 重置标志位
            this.isRotation = false;
            return;
        }


        //切换当前的状态
        if (this.curcurState === tipscurState.MOVE) {
            this.curcurState = tipscurState.ROTATE
        } else if (this.curcurState === tipscurState.ROTATE) {
            this.curcurState = tipscurState.MOVE
        }
    }

    onDoubleClick() {
        // 获取当前的节点缩放
        const scale = this.node.scale;

        let X = scale.x
        // 反转节点的 X 轴对称（即镜像翻转）
        X = scale.x > 0 ? -1 : 1;  // 当 scale.x 为正时，反转为负，否则反转为正

        // 如果需要反转 Y 轴，可以类似操作
        // scale.y = scale.y > 0 ? -1 : 1;

        // 更新节点的 scale
        this.node.setScale(new Vec3(X, scale.y, scale.z));


    }

}


interface polygonInfo {
    x: number;
    y: number;
    angle: number[];
    reverse: number;
}